package com.example.JavaWebApi.core.apiinterceptors;

import com.example.JavaWebApi.core.commonmodel.ResponseTypeEnum;
import com.example.JavaWebApi.core.jwthelper.JwtHelper;
import com.example.JavaWebApi.core.jwthelper.Tuple;
import com.example.JavaWebApi.model.entity.systemEntity.Userinfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: adks.process-api
 * @description: header上下文
 * @author: 杨泽
 * @create: 2022-06-23 11:35
 */
public class RequestHeaderContext {
    //Authorize头
    private static final ThreadLocal<String> REQUEST_HEADER_CONTEXT_THREAD_AUTHORIZE = new ThreadLocal<>();
    //用户ip
    private static final ThreadLocal<String> REQUEST_HEADER_CONTEXT_THREAD_IP = new ThreadLocal<>();
    //用户的token是否被验证过
    private static final ThreadLocal<Boolean> REQUEST_HEADER_CONTEXT_THREAD_IS_VALIDATE = new ThreadLocal<>();

    public static void setAuthorizeContext(String header, boolean isValid) {
        REQUEST_HEADER_CONTEXT_THREAD_AUTHORIZE.set(header);
        REQUEST_HEADER_CONTEXT_THREAD_IS_VALIDATE.set(isValid);
    }

    public static String getAuthorizeContext() {
        return REQUEST_HEADER_CONTEXT_THREAD_AUTHORIZE.get();
    }

    public static void removeAuthorizeContext() {
        REQUEST_HEADER_CONTEXT_THREAD_AUTHORIZE.remove();
        REQUEST_HEADER_CONTEXT_THREAD_IS_VALIDATE.remove();
    }

    public static void setIPContext(String ipStr) {
        REQUEST_HEADER_CONTEXT_THREAD_IP.set(ipStr);
    }

    public static String getIPContext() {
        return REQUEST_HEADER_CONTEXT_THREAD_IP.get();
    }

    public static void clean() {
        REQUEST_HEADER_CONTEXT_THREAD_AUTHORIZE.remove();
        REQUEST_HEADER_CONTEXT_THREAD_IP.remove();
        REQUEST_HEADER_CONTEXT_THREAD_IS_VALIDATE.remove();
    }

    public static Userinfo getUserinfo() {
        try {
            if (REQUEST_HEADER_CONTEXT_THREAD_IS_VALIDATE.get()) {
                return JwtHelper.getJwtInfo(REQUEST_HEADER_CONTEXT_THREAD_AUTHORIZE.get(), "userInfo", Userinfo.class);
            } else {
                Tuple<Boolean, ResponseTypeEnum> result = JwtHelper.verifyToken(REQUEST_HEADER_CONTEXT_THREAD_AUTHORIZE.get(), null);
                if (result.getItem()) {
                    REQUEST_HEADER_CONTEXT_THREAD_IS_VALIDATE.set(true);
                    return JwtHelper.getJwtInfo(REQUEST_HEADER_CONTEXT_THREAD_AUTHORIZE.get(), "userInfo", Userinfo.class);
                } else {
                    return null;
                }
            }

        } catch (Exception e) {
            Logger logger = LoggerFactory.getLogger(RequestHeaderContext.class);
            logger.error("用户token解析失败,非法用户！" + e.getMessage());
            return null;
        }

    }
}